var moment = require('moment');
const axios = require('axios');
const https = require('https');

const ora = require('ora');
const chalk = require('chalk');
const file = require('../src/file')
const ConsoleGrid = require("console-grid");
const words = require('../data/data.json')


let AUTH_TOKEN = ''
const exceptHost = '/api/v4/'

exports.run = function (start, end) {
  var host = ''
  file.isConfigExist().then(res => {
    if (res.success) {
      host = res.data.host + exceptHost
      AUTH_TOKEN = res.data.accessToken
      getData(start, end, host, AUTH_TOKEN)
    } else {
      console.log(chalk.red.bold(res.msg))
    }
  })
}

var getData = (start , end, host, AUTH_TOKEN) => {
  axios.defaults.baseURL = host;
  axios.defaults.headers.common['Authorization'] = 'Bearer ' + AUTH_TOKEN;
  axios.defaults.headers.post['Content-Type'] = 'application/json';
  let myAxios = axios.create({
    httpsAgent: new https.Agent({
      rejectUnauthorized: false
    })
  })
  let startDate = moment(start, "YYYY-MM-DD", true).isValid() ? start : moment().subtract(1, 'd').format('YYYY-MM-DD')
  let endDate = moment(end, "YYYY-MM-DD", true).isValid() ? end : moment().add(1, 'd').format('YYYY-MM-DD')
  let page = 1
  let perPage = 999
  console.log(`开始时间：${startDate}，结束时间：${endDate}`)
  const spinner = ora().start();
  spinner.color = 'yellow';
  spinner.text = '查询用户信息中...\n';
  myAxios.get('/user').then(userRes => {
    if (userRes.status === 200) {
      let { name: userName, id: userId } = userRes.data
      console.log('欢迎你，' + userName + '，你的id是：' + userId)
      spinner.text = '查询记录中...\n';
      Promise.all([
        myAxios.get(`/users/${userId}/events?after=${startDate}&before=${endDate}&page=${page}&per_page=${perPage}`),
        myAxios.get(`/projects?page=${page}&per_page=${perPage}`)
      ]).then(([eventRes, projectsRes]) => {
        spinner.text = '处理数据中...\n';
        if (eventRes.status !== 200) {
          console.log('查询最近事件失败！')
          return
        }
        if (projectsRes.status !== 200) {
          console.log('查询项目列表失败！')
          return
        }
        let projects = projectsRes.data.map(t => {
          return {
            projectId: t.id,
            projectName: t.name || '未知',
            description: t.description
          }
        })
        let event = eventRes.data.filter(t => t['push_data'] !== undefined && t['push_data']['commit_title'] !== null) // 去掉非提交日志类记录（创建项目、删除项目等）
        let formatData = event.map((t, index) => {
          let project = projects.filter(project => project.projectId === t['project_id'])[0]
          return {
            num: index,
            projectName: project !== undefined ? project['projectName'] : '未知', // 不在自己权限下的项目
            description: project !== undefined ? project['description'] : '未知',
            projectId: t['project_id'] || '未知',
            branch: t['push_data']['ref'] || '未知',
            time: moment(t['created_at']).format('YYYY-MM-DD HH:mm:ss') || '未知',
            commitTitle: t['push_data']['commit_title'] || '未知'
          }
        })
        spinner.stop()
        console.log(`查询完成，一共${event.length}条记录`)
        if (formatData.length <= 0) {
          console.log(chalk.yellow.bgRed.bold('是不是只顾着摸鱼了，并没有任何提交记录.'))
          // words.need_sentence.forEach((el, index) => {
          //   console.log(index + 1 + '. ' + el)
          // })
          return
        }
        var grid = new ConsoleGrid()
        var gridData = {
          option: {
            sortField: "time"
          },
          columns: [
            {
              id: "time",
              name: "时间",
              type: "string",
            },
            {
              id: "projectName",
              name: "项目名",
              type: "string",
            },
            {
              id: "projectId",
              name: "项目ID",
              type: "string",
            },
            {
              id: "description",
              name: "描述",
              type: "string",
            },
            {
              id: "branch",
              name: "分支名",
              type: "string",
            },
            {
              id: "commitTitle",
              name: "提交记录",
              type: "string",
            }
          ],
          rows: formatData
        }
        var lines = grid.render(gridData)
      })
    } else {
      console.log('查询用户失败！')
    }
  }).catch(err => {
    console.log('err', err)
  })
}